﻿using System;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Threading.Tasks;
using YiSha.Util;
using YiSha.Util.Extension;
using YiSha.Util.Model;
using YiSha.Data;
using YiSha.Data.Repository;
using YiSha.Entity.QixingManage;
using YiSha.Model.Param.QixingManage;
using YiSha.Model.Result.QixingManage;
using YiSha.Enum.QixingManage;

namespace YiSha.Service.QixingManage
{
    /// <summary>
    /// 创 建：admin
    /// 日 期：2023-03-19 19:46
    /// 描 述：订单详情服务类
    /// </summary>
    public class OrderDetailService :  RepositoryFactory
    {
        #region 获取数据
        public async Task<List<OrderDetailEntity>> GetList(OrderDetailListParam param)
        {
            var expression = ListFilter(param);
            var list = await this.BaseRepository().FindList(expression);
            return list.ToList();
        }

        public async Task<List<OrderDetailEntity>> GetPageList(OrderDetailListParam param, Pagination pagination)
        {
            var expression = ListFilter(param);
            var list= await this.BaseRepository().FindList(expression, pagination);
            return list.ToList();
        }

        public async Task<List<OrderDetailDto>> GetPageDetailList(OrderDetailListParam param, Pagination pagination)
        {
            StringBuilder strSql = new StringBuilder();
            var parameter = new List<DbParameter>();
            strSql.Append(@"SELECT a.Id,a.goods_id,a.order_id,a.pw_id,a.shop_id,a.goods_price,b.order_sn,b.shipping_user,b.ship_mobile,b.ordernumber,b.product_cnt,b.source_type,b.order_status,b.order_type,
                            b.receive_time,b.pay_time,b.shipping_time,b.create_time,b.payment_money,b.order_money,b.payment_method,b.address,b.district,
                            b.city,b.province,c.goods_name,c.goods_image,c.publish_status,d.shop_name FROM order_detail  a 
                            JOIN order_master b ON a.order_id=b.Id
                            JOIN goods_info c on a.goods_id=c.Id 
                            JOIN shop_info d on a.shop_id=d.Id 
                             where 1=1 ");

            if (!param.IsEmpty())
            {
                if (!param.order_sn.IsNullOrZero()) 
                {
                    strSql.Append(" and b.order_sn like @order_sn ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@order_sn",'%' + param.order_sn + '%'));
                }
                if (!param.shop_name.IsEmpty())
                {
                    strSql.Append(" and d.shop_name like @shop_name ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@shop_name", '%' + param.shop_name + '%'));
                }
                if (!param.goods_name.IsEmpty())
                {
                    strSql.Append(" and c.goods_name like @goods_name ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@goods_name", '%' + param.goods_name + '%'));
                }
                if (param.order_status!=-1)
                {
                    strSql.Append(" and b.order_status=@order_status ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@order_status", param.order_status));
                }
                if (!param.StartTime.IsEmpty())
                {
                    strSql.Append(" AND b.create_time>=@StartTime ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@StartTime", param.StartTime));
                }
                if (!param.EndTime.IsEmpty())
                {
                    param.EndTime = param.EndTime.Value.Date.Add(new TimeSpan(23, 59, 59));
                    strSql.Append(" AND b.create_time<=@EndTime ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@EndTime", param.EndTime));
                }
                if (!param.shopids.IsEmpty())
                {
                    if (param.shopids!="-1") 
                    {
                        var shoparr = TextHelper.SplitToArray<long>(param.shopids, ',');
                        if (shoparr.Count() > 0)
                        {
                            strSql.Append(" AND d.Id in(@shoparr) ");
                            parameter.Add(DbParameterExtension.CreateDbParameter("@shoparr", param.shopids));
                        }
                    }
                }
                if (!param.tenant_id.IsNullOrZero())
                {
                    strSql.Append(" AND a.tenant_id=@tenant_id ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@tenant_id", param.tenant_id));
                }
            }
            IEnumerable<OrderDetailDto> list = await this.BaseRepository().FindList<OrderDetailDto>(strSql.ToString(), parameter.ToArray(), pagination);

            foreach (var item in list)
            {
                item.source_type_doc = item.source_type.GetDescriptionByEnum<source_type_enum>();

                item.order_status_doc = item.order_status.GetDescriptionByEnum<orderStatus_enum>();

                item.payment_method_doc = item.payment_method.GetDescriptionByEnum<payment_method_enum>();

                item.publish_status_doc = item.publish_status.GetDescriptionByEnum<publish_status_enum>();
            }

            return list.ToList();
        }

        public async Task<List<OrderDetailDto>> GetNewPageColourDetailList(OrderDetailListParam param, Pagination pagination)
        {
            var parameter = new List<DbParameter>();
            string sql = string.Format("SELECT * from  order_detail where 1=1 ", param.orderid);
            if (!param.orderid.IsNullOrZero())
            {
                sql+=" and order_id=@order_id ";
                parameter.Add(DbParameterExtension.CreateDbParameter("@order_id", param.orderid));
            }
            
            IEnumerable<OrderDetailDto> list = await this.BaseRepository().FindList<OrderDetailDto>(sql, parameter.ToArray(), pagination);

            foreach (var item in list)
            {
                var sku= this.BaseRepository().FindList<GoodsSkuStockEntity>(t =>t.Id==item.skuid).Result.FirstOrDefault();
                item.skuname = sku?.sku_name;
                item.goods_image= sku?.pic;

                //查询车架号
                if (!item.productids.IsEmpty())
                {
                    var pwids = TextHelper.SplitToArray<long>(item.productids, ',');

                    var pws = this.BaseRepository().FindList<GoodsWarehouseEntity>(t => pwids.Contains(t.Id.Value)).Result.ToList().Select(t => t.VIN);

                    if (pws.Count() > 0)
                    {
                        item.VIN = string.Join(',', pws);
                    }
                }
            }
            return list.ToList();
        }

        public async Task<List<OrderDetailDto>> GetPageColourDetailList(OrderDetailListParam param, Pagination pagination)
        {
            StringBuilder strSql = new StringBuilder();
            var parameter = new List<DbParameter>();
            strSql.Append(@"SELECT a.Id,a.goods_id,a.order_id,a.productids,a.shop_id,a.colorid,b.order_sn,b.ordernumber,a.goods_cnt as product_cnt,
                            b.delivery_sn,b.delivery_company,
                            c.goods_name,e.attr_values as goods_image,e.attr_name as color,d.shop_name FROM order_detail  a 
                            JOIN order_master b ON a.order_id=b.Id
                            JOIN goods_info c on a.goods_id=c.Id 
                            JOIN shop_info d on a.shop_id=d.Id 
                            JOIN goods_attr e on a.colorid=e.Id 
                            where 1=1 ");

            if (!param.IsEmpty())
            {
                if (!param.order_sn.IsNullOrZero())
                {
                    strSql.Append(" and b.order_sn like @order_sn ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@order_sn", '%' + param.order_sn + '%'));
                }
                if (!param.orderid.IsNullOrZero())
                {
                    strSql.Append(" and a.order_id=@order_id ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@order_id",param.orderid));
                }
                if (!param.shop_name.IsEmpty())
                {
                    strSql.Append(" and d.shop_name like @shop_name ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@shop_name", '%' + param.shop_name + '%'));
                }
                if (!param.goods_name.IsEmpty())
                {
                    strSql.Append(" and c.goods_name like @goods_name ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@goods_name", '%' + param.goods_name + '%'));
                }
                if (param.order_status != -1)
                {
                    strSql.Append(" and b.order_status=@order_status ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@order_status", param.order_status));
                }
                if (!param.StartTime.IsEmpty())
                {
                    strSql.Append(" AND b.create_time>=@StartTime ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@StartTime", param.StartTime));
                }
                if (!param.EndTime.IsEmpty())
                {
                    param.EndTime = param.EndTime.Value.Date.Add(new TimeSpan(23, 59, 59));
                    strSql.Append(" AND b.create_time<=@EndTime ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@EndTime", param.EndTime));
                }
                if (!param.shopids.IsEmpty())
                {
                    if (param.shopids != "-1")
                    {
                        var shoparr = TextHelper.SplitToArray<long>(param.shopids, ',');
                        if (shoparr.Count() > 0)
                        {
                            strSql.Append(" AND d.Id in(@shoparr) ");
                            parameter.Add(DbParameterExtension.CreateDbParameter("@shoparr", param.shopids));
                        }
                    }
                }
                if (!param.tenant_id.IsNullOrZero())
                {
                    strSql.Append(" AND a.tenant_id=@tenant_id ");
                    parameter.Add(DbParameterExtension.CreateDbParameter("@tenant_id", param.tenant_id));
                }
            }
            IEnumerable<OrderDetailDto> list = await this.BaseRepository().FindList<OrderDetailDto>(strSql.ToString(), parameter.ToArray(), pagination);

            foreach (var item in list)
            {
                item.source_type_doc = item.source_type.GetDescriptionByEnum<source_type_enum>();

                item.order_status_doc = item.order_status.GetDescriptionByEnum<orderStatus_enum>();

                item.payment_method_doc = item.payment_method.GetDescriptionByEnum<payment_method_enum>();

                item.publish_status_doc = item.publish_status.GetDescriptionByEnum<publish_status_enum>();

                //查询车架号
                if (!item.productids.IsEmpty())
                {
                    var pwids = TextHelper.SplitToArray<long>(item.productids, ',');

                    var pws = this.BaseRepository().FindList<GoodsWarehouseEntity>(t => pwids.Contains(t.Id.Value)).Result.ToList().Select(t => t.VIN);

                    if (pws.Count() > 0)
                    {
                        item.VIN = string.Join(',', pws);
                    }
                }
            }

            return list.ToList();
        }

        public async Task<OrderDetailEntity> GetEntity(long id)
        {
            return await this.BaseRepository().FindEntity<OrderDetailEntity>(id);
        }

        public async Task<List<OrderDetailEntity>> GetList(long orderid)
        {
            var list=await this.BaseRepository().FindList<OrderDetailEntity>(t=>t.order_id== orderid);

            return list.ToList();
        }

        public async Task<OrderDetailEntity> GetQueryOrderEntity(long orderid)
        {
            return await this.BaseRepository().FindEntity<OrderDetailEntity>(t=>t.order_id== orderid);
        }

        public OrderDto GetGoodsOrderEntity(long id)
        {
            if (id.IsNullOrZero())
            {
                return null;
            }
            StringBuilder strSql = new StringBuilder();
            var parameter = new List<DbParameter>();
            strSql.Append(@"SELECT a.Id,a.order_sn,a.shipping_user,a.ship_mobile,a.ordernumber,a.product_cnt,a.source_type,a.order_status,a.order_type,
                            a.receive_time,a.pay_time,a.shipping_time,a.create_time,a.payment_money,a.order_money,a.payment_method,a.address,a.district,
                            a.city,a.province FROM order_master  a  
                             ");
            strSql.Append(" where a.Id=@order_id ");
            parameter.Add(DbParameterExtension.CreateDbParameter("@order_id",id));
            return this.BaseRepository().FindList<OrderDto>(strSql.ToString(),parameter.ToArray()).Result.FirstOrDefault();
        }
        #endregion

        #region 提交数据
        public async Task SaveForm(OrderDetailEntity entity)
        {
            if (entity.Id.IsNullOrZero())
            {
                entity.Create();
                await this.BaseRepository().Insert(entity);
            }
            else
            {
                
                await this.BaseRepository().Update(entity);
            }
        }


        public async Task OrderDetailSaveFormJson(OrderDetailEntity entity)
        {
            await this.BaseRepository().Update(entity);
        }

        

        public async Task DeleteForm(string ids)
        {
            long[] idArr = TextHelper.SplitToArray<long>(ids, ',');
            await this.BaseRepository().Delete<OrderDetailEntity>(idArr);
        }
        #endregion

        #region 私有方法
        private Expression<Func<OrderDetailEntity, bool>> ListFilter(OrderDetailListParam param)
        {
            var expression = LinqExtensions.True<OrderDetailEntity>();
            if (param != null)
            {
                if (!param.tenant_id.IsNullOrZero())
                {
                    expression = expression.And(t => t.tenant_id == param.tenant_id);
                }
            }
            return expression;
        }
        #endregion
    }
}
